package br.ita.doacoes.core.templates;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Id;
import javax.persistence.Query;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Id;
import javax.persistence.Query;


public class GenericDAOJPA implements DAO{
	
	private Class classePersistente;
	
	public GenericDAOJPA(Class classePersistente) {
		this.classePersistente = classePersistente;
	}

	public void delete(Object o) {
		EntityManager em = JPAUtil.getEntityManager();
		EntityTransaction t = em.getTransaction();
		t.begin();
		o = em.merge(o);
		em.remove(o);
		t.commit();
	}

	public Object getById(Object o) {
		Object idValue = null;
		try {


			for (Method f : classePersistente.getDeclaredMethods()) {
				if (f.isAnnotationPresent(Id.class)) {
					idValue = f.invoke(o);
				}
			}
			for(Field f :classePersistente.getDeclaredFields()){
				if(f.isAnnotationPresent(Id.class)){
					String getterName = "get" + f.getName().substring(0,1).toUpperCase() + f.getName().substring(1); 
					Method m = classePersistente.getMethod(getterName);
					idValue = m.invoke(o);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		EntityManager em = JPAUtil.getEntityManager();
		Object retorno = em.find(classePersistente,idValue);
		return retorno;
	}

	public List getList() {
		EntityManager em = JPAUtil.getEntityManager();
		Query q = em.createQuery("select o from "+ classePersistente.getName() +" o");
		List list = q.getResultList();
		return list;
	}

	public void insert(Object o) {
		EntityManager em = JPAUtil.getEntityManager();
		EntityTransaction t = em.getTransaction();
		t.begin();
		em.persist(o);
		t.commit();
	}

	public void update(Object o) {
		EntityManager em = JPAUtil.getEntityManager();
		EntityTransaction t = em.getTransaction();
		t.begin();
		em.merge(o);
		t.commit();
	}

}

